#include "videorecever.h"
#include <QImage>
#include <QBuffer>
#include <QThread>

VideoRecever::VideoRecever(QString ip, quint16 port, QObject *parent) : QObject(parent)
{
    socket = new QUdpSocket(this);
    socket->bind(QHostAddress::AnyIPv4, port, QAbstractSocket::ReuseAddressHint);
    socket->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption, 300*2048);
    socket->joinMulticastGroup(QHostAddress(ip));

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &VideoRecever::onTimeout);
    timer->start(1000);
}

void VideoRecever::onReadyRead()
{
    static QByteArray imageBytes;
    static QBuffer buffer(&imageBytes);
    buffer.open(QIODevice::WriteOnly);
    static int count = 0;
    static int prevPackNum = 0;
    while (TaskSignal)
    {
        if (socket->hasPendingDatagrams())
        {
            ImagePackage1 pack = {};
            memset(&pack, 0, sizeof(ImagePackage1));
            socket->readDatagram((char *)&pack, sizeof(ImagePackage1));
//            if (pack.packNum == -1) {
//                emit getFps(0);
//                continue;
//            }
            if (pack.packNum < prevPackNum)
            {
                QImage loadedImage;
                loadedImage.loadFromData(imageBytes, "JPG");

                ++fps;

                emit recvComplete(loadedImage);

                prevPackNum = pack.packNum;
                buffer.seek(0);
                imageBytes.clear();
                count = 0;
            }
            buffer.write(pack.data, pack.packTaken);
            count += pack.packTaken;
            prevPackNum = pack.packNum;
        }
    }
}

void VideoRecever::endTask()
{
    TaskSignal = false;
}

void VideoRecever::onTimeout()
{
    emit getFps(fps);
    qDebug() << "FPS:" << fps;
    fps = 0;
}
